package cn.icanci.template.handler;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: icanci
 * @ProjectName: kangaroo-orm
 * @PackageName: cn.icanci.template.handler
 * @Date: Created in 2020/8/31 15:59
 * @ClassAction: 返回结果集封装为集合
 */
public class ListBeanHandler<T> implements IResultSetHandler<List<T>> {

    private Class<T> classType;

    public ListBeanHandler(Class<T> classType) {
        this.classType = classType;
    }

    @Override
    public List<T> handler(ResultSet rs) throws Exception {
        if (null == rs) {
            return new ArrayList<T>();
        }
        List<T> ts = new ArrayList<>();
        while (rs.next()) {
            T obj = classType.newInstance();
            ts.add(obj);
            BeanInfo beanInfo = Introspector.getBeanInfo(classType, Object.class);
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd : pds) {
                String columnName = pd.getName();
                Object value = rs.getObject(columnName);
                pd.getWriteMethod().invoke(obj, value);
            }
        }
        return ts;
    }
}
